package com.oilsection.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oilsection.demo.controller.req.ZrEventImportReq;
import com.oilsection.demo.controller.req.ZrdImportReq;
import com.oilsection.demo.controller.req.ZrdPageQueryReq;
import com.oilsection.demo.controller.res.ZrdPageQueryResponse;
import com.oilsection.demo.mapper.ZrdMapper;
import com.oilsection.demo.po.Zrd;
import com.oilsection.demo.service.ZrdService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ZrdServiceImpl extends ServiceImpl<ZrdMapper, Zrd> implements ZrdService {

    private final ZrdMapper zrdMapper;

    @Override
    public ZrdPageQueryResponse getZrdPage(ZrdPageQueryReq req) {
        Page<Zrd> page = page(new Page<>(req.getPage(), req.getPageSize()), new LambdaQueryWrapper<Zrd>().eq(ObjUtil.isNotEmpty(req.getKqName()), Zrd::getKqName, req.getKqName()).eq(ObjUtil.isNotEmpty(req.getZrdName()), Zrd::getName, req.getZrdName()));
        return ZrdPageQueryResponse.builder().len(page.getTotal()).zrdList(BeanUtil.copyToList(page.getRecords(), ZrdPageQueryResponse.ZrdQueryDto.class)).build();
    }

    @Override
    public void deleteZrdById(Long id) {
        removeById(id);
    }

    @Override
    public void updateLocationById(Zrd req) {
        lambdaUpdate().eq(Zrd::getId, req.getId()).set(Zrd::getXPoint, req.getXPoint()).set(Zrd::getYPoint, req.getYPoint()).update();
    }

    @Override
    @Transactional
    public void importZrd(List<ZrdImportReq> reqs) {
        List<Zrd> zrds = new ArrayList<>();
        for (ZrdImportReq req : reqs) {
            Zrd zrd = new Zrd();
            zrd.setKqName(req.getKqName());
            zrd.setName(req.getZrdName());
            zrd.setXPoint(req.getXPoint());
            zrd.setYPoint(req.getYPoint());
            zrds.add(zrd);
        }
        saveBatch(zrds);
    }
}
